package com.wego.controller;

import com.wego.bean.StateBean;
import com.wego.common.sms.utils.SendSmsUtil;
import com.wego.entity.domain.Admin;
import com.wego.entity.domain.User;
import com.wego.service.AdminService;
import com.wego.service.UserService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @className: LoginController
 * @description: 登录控制器
 * @author: Li Chuanwei
 * @date: 2023/07/08 8:45
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Slf4j
@Controller
public class LoginController {
    @Autowired
    AdminService adminService;

    @Autowired
    UserService userService;

    @RequestMapping("manager/loginIn")
    public @ResponseBody StateBean adminLoginIn(Admin admin, HttpSession session){
        if(admin.getPhone().equals(""))
            admin.setPhone(null);
        if(admin.getAccount().equals(""))
            admin.setAccount(null);
        if(admin.getPassword().equals(""))
            admin.setPassword(null);
        if(adminService.isExistAdmin(admin)){
            admin = adminService.selectOne(admin);
            session.setMaxInactiveInterval(1800);
            session.setAttribute("admin", admin);
            return new StateBean(200,"成功");
        }
        else
            return new StateBean(0,"失败");
    }

    @RequestMapping("user/loginIn")
    public @ResponseBody StateBean userLoginIn(User user, HttpSession session){
        if(user.getPhone().equals(""))
            user.setPhone(null);
        if(user.getAccount().equals(""))
            user.setAccount(null);
        if(user.getPassword().equals(""))
            user.setPassword(null);
        if(userService.isExistUser(user)){
            user = userService.selectOne(user);
            session.setMaxInactiveInterval(1800);
            session.setAttribute("user", user);
            return new StateBean(200,"成功");
        }
        else
            return new StateBean(0,"失败");
    }

    @RequestMapping("user/LoginOut")
    public String userLoginOut(HttpSession session){
        // 清除HttpSession中的数据
        session.invalidate();
        return "redirect:/userIndex"; // 重定向到登录页面
    }

    @RequestMapping("manager/LoginOut")
    public String managerLoginOut(HttpSession session){
        // 清除HttpSession中的数据
        session.invalidate();
        return "manager/login";
    }

    @RequestMapping("/getCode")
    public @ResponseBody StateBean getCode(String phone){
        String[] phoneNumbers = {phone};
        String code = SendSmsUtil.sendSms(phoneNumbers);
        return new StateBean(200,code);
    }
}
